<template>
  <dynamic-load-data ref="dynamicLoadData" :loading="logLoading" :dynamicData="logData" />
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch, onUnmounted } from "vue"
import { getlogs } from 'src/api/designerTool'
import { designerStore } from 'src/stores/designerTool/designerTool'
import { instancesState } from 'src/utils/designerTool/constants'
import DynamicLoadData from '../../components/dynamicLoadData.vue'
import { logMessageHandle } from 'src/utils/designerTool/toole'
import { ElMessage } from 'element-plus'
const store = designerStore()
const dialogVisible = ref(false)
const title = ref('运行日志')
const rowId = ref('')
const end_time = ref(-1)
const logData = ref('')
const logLoading = ref(false)
const timingRun = ref()
const instanceRunning = computed(() => {
  return store.instanceState === instancesState.Running
})
const isInstance = computed(() => {
  return store.workflowInfo.id && store.instanceId
})
watch(() => store.instanceId, (newData, oldData) => {
  logInit()
})
// watch(() => store.instanceState, (newData, oldData) => {
//   if (instanceRunning.value) {
//     logInit()
//     getInstancesLog()
//   }
// })
onUnmounted(() => {
  clearTimeout(timingRun.value)
  dialogVisible.value = false
})
function init() {
  dialogVisible.value = true
  nextTick(() => {
    logInit()
    getInstancesLog()
  })
}
function logInit() {
  end_time.value = -1
  logData.value = ''
}
function getInstancesLog() {
  if (isInstance.value) {
    logLoading.value = true
    let filepathStr=`error_${store.operator_id}.log`
    if(store.instancesRunData.state=='success'){
      filepathStr=`output_${store.operator_id}.log`
    }
    getlogs(store.project_id,store.workflowInfo.id, store.instanceId, {
      filepath:filepathStr
      // start_time: '',
      // end_time: this.$moment(new Date()).format('YYYYMMDDHHmmss')
    }).then((res: any) => {
      logData.value=res.data.replace(/\n/g, '<br>')
      if (dialogVisible.value && instanceRunning.value) {
        runTimeout()
      }
    }).finally(() => {
      logLoading.value = false
    })
  }
}
function runTimeout() {
  timingRun.value = setTimeout(() => {
    if (dialogVisible.value) {
      getInstancesLog()
    }
  }, 1000)
}
defineExpose({init})
</script>

<style lang="scss" scoped></style>
